<script setup lang="ts">
import { isNullOrEmpty } from '@/utils/functions'
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import phone from "./components/phone.vue";
import regist from "./components/regist.vue";
import dayIcon from "@/assets/images/svg/day.svg?component";
import darkIcon from "@/assets/images/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { storageLocal } from "@pureadmin/utils";

import md5 from "blueimp-md5";
import { getSelfInfo, getCaptcha } from "@/api/user";
import { setUserKey } from "@/utils/auth";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { addPathMatch } from "@/router/utils";
import { resetRouter } from "@/router/index";
import {
  initUnit,
  usePageVariablesStoreHook
} from "@/store/modules/pageVariables";
defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();
const codeImg = ref("");
// const ruleForm = reactive({
//   loginName: "admin",
//   password: "Admin123!",
//   captchaValue: "",
//   captchaId: null
// });
const ruleForm = reactive({
  loginName: "yclmxAdmin",
  password: "yclmxAdmin123!",
  captchaValue: "",
  captchaId: null
});
const operates = [
  {
    title: "手机号登录",
    currentPage: 1
  },
  {
    title: "账号注册",
    currentPage: 2
  }
];
const currentPage = computed(() => {
  return useUserStoreHook().currentPage;
});
const onLogin = async (formEl: FormInstance | undefined) => {
  storageLocal().removeItem("manage");
  storageLocal().removeItem("operate");
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      let copy = JSON.parse(JSON.stringify(ruleForm));
      copy.password = md5(copy.password);
      useUserStoreHook()
        .loginByUsername(copy)
        .then(res => {
          // 全部采取静态路由模式
          getSelfInfo().then(res => {
            let data = res.result;
            setUserKey(data.userInfo.nickname, data.permissions, data.userInfo);
            usePageVariablesStoreHook().clear();
            initUnit().then(() => {
              resetRouter();
              message("登录成功", { type: "success" });
            });
            // usePermissionStoreHook().handleWholeMenus([]);
            // addPathMatch();
            // router.push("/");
          });
        }).catch(() => {
          getCodeImg();
        }).finally(() => {
          setTimeout(() => {
            loading.value = false;
          }, 1000);
        });
    } else {
      return fields;
    }
  });
};
const getCodeImg = () => {
  getCaptcha().then(res => {
    codeImg.value = res.result.captchaImg;
    ruleForm.captchaId = res.result.captchaId;
  });
};

onMounted(() => {
  getCodeImg();
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch v-model="dataTheme" inline-prompt :active-icon="dayIcon" :inactive-icon="darkIcon"
        @change="dataThemeChange" />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ isNullOrEmpty( title ) }}</h2>
          </Motion>

          <el-form v-if="currentPage === 0" ref="ruleFormRef" :model="ruleForm" :rules="loginRules" size="large">
            <Motion :delay="100">
              <el-form-item :rules="[
                {
                  required: true,
                  message: '请输入账号',
                  trigger: 'blur'
                }
              ]" prop="loginName">
                <el-input v-model="ruleForm.loginName" clearable placeholder="账号" :prefix-icon="useRenderIcon(User)" />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input v-model="ruleForm.password" clearable show-password placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)" />
              </el-form-item>
            </Motion>

            <Motion :delay="200">
              <el-form-item prop="captchaValue">
                <el-input v-model="ruleForm.captchaValue" :placeholder="'请输入验证码'" @keyup.enter="onLogin(ruleFormRef)"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')">
                  <template v-slot:append>
                    <!-- <ReImageVerify v-model:code="imgCode" /> -->
                    <el-image style="height: var(--el-input-height)" :src="codeImg" @click="getCodeImg"></el-image>
                  </template>
                </el-input>
              </el-form-item>
            </Motion>
            <Motion :delay="250">
              <el-button class="w-full mt-4" size="default" type="primary" :loading="loading"
                @click="onLogin(ruleFormRef)">
                登录
              </el-button>
            </Motion>
            <Motion :delay="300">
              <el-form-item>
                <div class="w-full h-[20px] flex justify-between items-center mt-[10px]">
                  <el-button v-for="(item, index) in operates" :key="index" class="w-full mt-4" size="default" @click="
                    useUserStoreHook().SET_CURRENTPAGE(item.currentPage)
                    ">
                    {{ isNullOrEmpty( item.title ) }}
                  </el-button>
                </div>
              </el-form-item>
            </Motion>
          </el-form>
          <phone v-if="currentPage === 1" />
          <regist v-if="currentPage === 2" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
